<?php
/**
 * Created by PhpStorm.
 * User: fengdh
 * Date: 2018/5/11
 * Time: 9:49
 */

namespace common\utils;

use yii\helpers\ArrayHelper;

class ArrayUtils
{
    /**
     * 根据数组key获取数组value
     * @param array $data
     * @param $key
     * @param string $defaultValue
     * @return string
     */
    public static function  getArrayValueByKey(array $data, $key, $defaultValue = '') {
        return isset($data[$key]) ? $data[$key] : $defaultValue;
    }


    /**
     * 对象转数组
     * @param $array
     * @return array
     */
    public static function objectToArray($array) {
        if (is_object($array)) {
            $array = (array)$array;
        }
        if (is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = self::objectToArray($value);
            }
        }
        return $array;
    }

    public static function arrayIndex($array,$key)
    {
        $result = [];
        foreach ($array as $element) {
            $value = ArrayHelper::getValue($element, $key);
            if (ArrayHelper::keyExists($value, $result)) {
                $list = [];
                foreach ($result[$value] as $item) {
                    array_push($list, $item);
                }
                array_push($list, $element);
                $result[$value] = $list;
            } else {
                $result[$value] = [$element];
            }
        }
        return $result;
    }

    public static function convertObjectToArray($stdClassObject)
    {
        $_array = is_object($stdClassObject) ? get_object_vars($stdClassObject) : $stdClassObject;

        foreach ($_array as $key => $value) {
            $value = (is_array($value) || is_object($value)) ? self::convertObjectToArray($value) : $value;
            $array[$key] = $value;
        }

        return empty($array) ? []:$array;
    }
    /**
     * 对象转换为数组
     * @param $object
     * @return array
     */
    public static function  object2array($object) {
        $array = [];
        if (is_object($object)) {
            foreach ($object as $key => $value) {
                $array[$key] = $value;
            }
        }
        else {
            $array = $object;
        }
        return $array;
    }

    /**
     * 数组转换为对象
     * @param $array
     * @return stdClass
     */
    public static function array2object($array) {
        if (is_array($array)) {
            $obj = new StdClass();
            foreach ($array as $key => $val){
                $obj->$key = $val;
            }
        }
        else { $obj = $array; }
        return $obj;
    }
}